package com.yqb.study.common.session;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.yqb.study.constant.key.ICookieKey;
import com.yqb.study.util.CookieUtil;

/**
 * 线程使用session存放
 */
public class RedisSessionContextHolder {

	// 每个用户的一次请求都有一个线程为其服务,这个线程中对应的用户session应该是唯一的
	// 通过redisSessionContextHolder.set(new
	// RedisSessionImpl(token))将线程中的唯一session保存到ThreadLocalMap
	// 通过redisSessionContextHolder.get(),从ThreadLocalMap中取出以redisSessionContextHolder为key的线程使用session
	private static final ThreadLocal<IRedisSession> redisSessionContextHolder = new ThreadLocal<IRedisSession>();

	/**
	 * 获取线程session 线程可能维护在线程池中所以每次取新的session
	 */
	public static IRedisSession getThreadRedisSession() {

		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		// 获取request
		HttpServletRequest request = attributes.getRequest();

		// 查询cookie,取出token
		String token = CookieUtil.getToken(request, ICookieKey.TOKEN_KEY);

		// 从redis中根据token取出对应session
		IRedisSession redisSession = new RedisSessionImpl(token);
		redisSessionContextHolder.set(redisSession);

		return redisSession;
	}

	/**
	 * 清除线程session
	 */
	public static void clearThreadRedisSession() {
		redisSessionContextHolder.remove();
	}
}
